﻿using JuCheap.Core.Interfaces;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace JuCheap.Core.Web.Services
{
    public class HostedBackgroundService : BackgroundService
    {
        private readonly IServiceProvider _sp;
        private readonly ILogger<HostedBackgroundService> _logger;

        public HostedBackgroundService(IServiceProvider sp, ILogger<HostedBackgroundService> logger)
        {
            _sp = sp;
            _logger = logger;
        }


        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                if (DateTime.Now - DateTime.Today < TimeSpan.FromHours(23))
                {
                    await Task.Delay(TimeSpan.FromMinutes(40), stoppingToken);
                    continue;
                }

                try
                {
                    using (var scope = _sp.CreateScope())
                    {
                        var attend = scope.ServiceProvider.GetRequiredService<ICheckWorkAttendanceService>();
                        await attend.CheckAttendance();
                    }
                    
                    await Task.Delay(TimeSpan.FromMinutes(40), stoppingToken);
                }
                catch (Exception ex)
                {
                    _logger.LogWarning(ex, "Exception When CheckAttendance!");
                }
            }
        }
    }
}
